/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.serializer.plugin;

import at.schauer.gregor.vienna.exception.ViennaException;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Gregor Schauer
 */
public class CipherPlugin<T> extends DefaultSerializerPlugin<T> {
	public enum EncryptMode {NONE, KEY, VALUE, KEY_VALUE}

	protected Key key;
	protected byte[] initVector;
	protected EncryptMode mode;
	protected IvParameterSpec ips;
	protected Cipher encryptCipher;
	protected Cipher decryptCipher;

	protected CipherPlugin(Key key, byte[] initVector, EncryptMode mode) {
		this.key = key;
		this.initVector = initVector;
		this.mode = mode;

		this.ips = new IvParameterSpec(initVector);
		this.encryptCipher = createEncryptCipher();
		this.decryptCipher = createDecryptCipher();
	}

	protected Cipher createEncryptCipher() {
		return createCipher(key, ips, Cipher.ENCRYPT_MODE);
	}

	protected Cipher createDecryptCipher() {
		return createCipher(key, ips, Cipher.DECRYPT_MODE);
	}

	protected static Cipher createCipher(Key key, IvParameterSpec ips, int mode) {
		try {
			Cipher cipher = Cipher.getInstance(key.getAlgorithm());
			cipher.init(mode, key);
			return cipher;
		} catch (Exception e) {
			throw new ViennaException(e);
		}
	}

	@Override
	public Map<String, Object> preConstruct(Map<String, Object> map, Class<? extends T> clazz) {
		return process(map, decryptCipher);
	}

	@Override
	public Map<String, Object> postFinalize(Map<String, Object> map, T obj) {
		return process(map, encryptCipher);
	}

	protected Map<String, Object> process(Map<String, Object> map, Cipher cipher) {
		if (mode == EncryptMode.NONE) {
			return map;
		}
		boolean encr = cipher == encryptCipher;
		Map<String, Object> result = new HashMap<String, Object>();

		try {
			if (mode == EncryptMode.KEY) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					if (entry.getKey() == null) {
						continue;
					}
					String newKey = decode(cipher.doFinal(encode(String.valueOf(entry.getKey()), encr)), encr);
					result.put(newKey, entry.getValue());
				}
			} else if (mode == EncryptMode.VALUE) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					if (entry.getValue() == null) {
						continue;
					}
					String newValue = decode(cipher.doFinal(encode(String.valueOf(entry.getValue()), encr)), encr);
					result.put(entry.getKey(), newValue);
				}
			} else if (mode == EncryptMode.KEY_VALUE) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					String newKey = entry.getKey() == null ? entry.getKey() :
							decode(cipher.doFinal(encode(String.valueOf(entry.getKey()), encr)), encr);
					Object newValue = entry.getValue() == null ? entry.getValue() :
							decode(cipher.doFinal(encode(String.valueOf(entry.getValue()), encr)), encr);
					result.put(newKey, newValue);
				}
			}
			return result;
		} catch (Exception e) {
			throw new ViennaException(e);
		}
	}

	protected static String decode(byte[] bytes, boolean encr) {
		return encr ? new String(Base64.encode(bytes)) : new String(bytes);
	}

	protected static byte[] encode(String str, boolean encr) {
		return encr ? str.getBytes() : Base64.decode(str.getBytes());
	}
}
